#!/bin/sh

MODE=$1
function networkUp() {
  echo "RootCA启动";
  cd $GOPATH/src/github.com/hyperledger/fabric-ca/bin
  mkdir ca-server
  #把文档都拉到bin目录下
  cp -f docker-rootca.yaml ./ca-server
  cp -f docker-intermediaca1.yaml ./ca-server
  cp -f docker-intermediaca2.yaml ./ca-server
  cp -f docker-intermediacatls1.yaml ./ca-server
  cp -f docker-intermediacatls2.yaml ./ca-server


  cd ca-server
  fabric-ca-server init -b admin:adminpw --home ./rootca
  docker-compose -f docker-rootca.yaml up -d

  echo "IntermediaCA1 start";
  fabric-ca-server init -b admin1:adminpw1 -u http://admin:adminpw@localhost:7054 --home ./intermediaca1
  fabric_port="7055"
  sed -i "s/^port:.*$/port: $fabric_port/g" ./intermediaca1/fabric-ca-server-config.yaml
  docker-compose -f docker-intermediaca1.yaml up -d

  echo "IntermediaCAtls1 start";
  fabric-ca-server init -b admin1:adminpw1 -u http://admin:adminpw@localhost:7054 --home ./intermediacatls1
  fabric_port="8055"
  sed -i "s/^port:.*$/port: $fabric_port/g" ./intermediacatls1/fabric-ca-server-config.yaml
  docker-compose -f docker-intermediacatls1.yaml up -d

  echo "IntermediaCA2启动 start";
  fabric-ca-server init -b admin2:adminpw2 -u http://admin:adminpw@localhost:7054 --home ./intermediaca2
  fabric_port="7056"
  sed -i "s/^port:.*$/port: $fabric_port/g" ./intermediaca2/fabric-ca-server-config.yaml
  docker-compose -f docker-intermediaca2.yaml up -d

  echo "IntermediaCAtls2 start";
  fabric-ca-server init -b admin2:adminpw2 -u http://admin:adminpw@localhost:7054 --home ./intermediacatls2
  fabric_port="8056"
  sed -i "s/^port:.*$/port: $fabric_port/g" ./intermediacatls2/fabric-ca-server-config.yaml
  docker-compose -f docker-intermediacatls2.yaml up -d

  docker ps -a
}

function networkDown() {
  cd $GOPATH/src/github.com/hyperledger/fabric-ca/bin
  cd ca-server
  echo "RootCA stop"
  docker-compose -f docker-rootca.yaml down
  echo "IntermediaCA1 stop"
  docker-compose -f docker-intermediaca1.yaml down
  echo "IntermediaCA2 stop"
  docker-compose -f docker-intermediaca2.yaml down
  echo "IntermediaCAtls1 stop"
  docker-compose -f docker-intermediacatls1.yaml down
  echo "IntermediaCAtls2 stop"
  docker-compose -f docker-intermediacatls2.yaml down
  docker ps -a
  cd ..
  rm -rf ca-server
}


if [ "$MODE" == "up" ]; then
  networkUp
elif [ "$MODE" == "down" ]; then
  networkDown
else
  exit 1
fi
